AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
util.PrecacheSound( "Airboat_engine_idle" )
util.PrecacheSound( "Boulder.ImpactHard" )
util.PrecacheSound( "Airboat_engine_stop" )
util.PrecacheSound( "Airboat_engine_start" )
util.PrecacheSound( "Airboat_skid_rough" )


function ENT:Initialize()
	self.BaseClass.Initialize(self)
	self.vein = nil
	self.connectedtovein = false
	self.on = false
	self.drilling = false
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
    local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	if not (WireAddon == nil) then
		self.WireDebugName = self.PrintName
		self.Inputs = WireLib.CreateInputs(self.Entity, { "On" })
		self.Outputs = WireLib.CreateSpecialOutputs(self.Entity, { "Mineral", "Veinsize", "Output" }, { "STRING","STRING","NORMAL" })
		Wire_TriggerOutput(self.Entity, "Mineral", "Not Connected")
		Wire_TriggerOutput(self.Entity, "Veinsize", "Not Connected")
		Wire_TriggerOutput(self.Entity, "Output", 0)
	end
end

function ENT:ToggleOnOff(value)
	
	if self.on then
		if not value then
			self:StopSound( "Airboat_engine_idle" )
			self:StopSound( "Airboat_engine_fullthrottle" )
			self:EmitSound( "Airboat_engine_stop" )
			Wire_TriggerOutput(self.Entity, "Output", 0)
			self.on = false
		end
	else
		if value then
			--self:EmitSound( "d3_citadel.podarm_move_start" )
			self:EmitSound( "Airboat_engine_start" )
			timer.Create( "gdrillstart" .. self:EntIndex(), 2.15, 1, function()
				self:EmitSound( "Airboat_engine_idle" )
				self.on = true
			end )
		else
			timer.Destroy("gdrillstart" .. self:EntIndex())
			self:StopSound( "Airboat_engine_start" )
		end
	end
end

function ENT:TriggerInput(iname, value)
	if (iname == "On") then
		if value > 0 then
			self:ToggleOnOff(true)
		else
			self:ToggleOnOff(false)
		end
	end
end

function ENT:Use( activator, caller )
	if ( activator:IsPlayer() ) then
		if (not activator:KeyDownLast(IN_USE)) then
			if (not self.connectedtovein) then
				local orgin_ents = ents.FindInSphere(self:GetPos(),30)
				for k, v in pairs(orgin_ents) do
					if (v:GetClass() == "vein") then
						self.vein = v
						v.linked = true
						self.connectedtovein = true
						self:SetPos(v:GetPos())
						local ang = v.hitnormal:Angle()
						ang.pitch = ang.pitch + 90
						self:SetAngles(ang)
						local phys = self:GetPhysicsObject()
						if phys and phys:IsValid() then
							phys:EnableMotion(false) -- Freezes the object in place.
						end
						Wire_TriggerOutput(self.Entity, "Mineral", "Not Drilling")
						Wire_TriggerOutput(self.Entity, "Veinsize", "Not Drilling")
						Wire_TriggerOutput(self.Entity, "Output", 0)
					end
				end
			end
		end
	end
end

function ENT:Unlinkfromvein()
	if self.vein then
		self.vein.linked = false
	end
	local phys = self:GetPhysicsObject()
	if phys and phys:IsValid() then
		phys:EnableMotion(true) -- Freezes the object in place.
		phys:Wake()
	end
	self.vein = nil
	Wire_TriggerOutput(self.Entity, "Mineral", "Not Connected")
	Wire_TriggerOutput(self.Entity, "Veinsize", "Not Connected")
	Wire_TriggerOutput(self.Entity, "Output", 0)
	self.connectedtovein = false
	self.drilling = false
end

function ENT:OnRemove()
	self:StopSound( "Airboat_engine_idle" )
	timer.Destroy("gdrillstart" .. self:EntIndex())
	if self.connectedtovein then
		self.vein.linked = false
	end
	self.BaseClass.OnRemove(self)
end

function ENT:Detonate()
	local effectdata = EffectData()
	effectdata:SetOrigin(self:GetPos())
	effectdata:SetNormal(Vector(0,0,1))
	effectdata:SetScale(1)
	util.Effect("Explosion", effectdata)
	self.Entity:Remove()
end

function ENT:Drill()
	if self.connectedtovein then
		if not self.drilling then
			self.drilling = true
		else
			local RD = CAF.GetAddon("Resource Distribution")
			local SelfEn = RD.ConsumeResource(self,"energy",200)
			if (SelfEn < 200) then
				self:ToggleOnOff(false)
			else
				RD.ConsumeResource(self,"energy",200)
				local chn = math.random(1,100)
				if (chn > 70) then
					self:EmitSound( "Boulder.ImpactHard" )
					util.ScreenShake( self:GetPos(), 5, 5, 1, 700 )
				end
				local mined, gotmins = self.vein:Dig(1)
				if mined then
					if not gotmins.bm then self:EmitSound( "Airboat_skid_rough" ) end
					if not (WireAddon == nil) then
						Wire_TriggerOutput(self.Entity, "Mineral", gotmins.name)
						Wire_TriggerOutput(self.Entity, "Veinsize", gotmins.veinsize)
						Wire_TriggerOutput(self.Entity, "Output", gotmins.amount)
					end
					local SM = CAF.GetAddon("Selling Machine")
					
					if (SM.gResources[gotmins.name].group == "ore") then gotmins.name = gotmins.name .. " Ore" end
					local tostore = RD.SupplyResource(self, gotmins.name, gotmins.amount)
					if (tostore > 0) then
						self:ToggleOnOff(false)
					end
				else
					self:Unlinkfromvein()
				end
				
				
				local Smoke = ents.Create("env_smoketrail")
				Smoke:SetKeyValue("opacity", 1)
				Smoke:SetKeyValue("spawnrate", 10)
				Smoke:SetKeyValue("lifetime", 3)
				Smoke:SetKeyValue("startcolor", "80 80 80")
				Smoke:SetKeyValue("endcolor", "180 180 180")
				Smoke:SetKeyValue("minspeed", 15)
				Smoke:SetKeyValue("maxspeed", 30)
				Smoke:SetKeyValue("startsize", 10)
				Smoke:SetKeyValue("endsize", 50)
				Smoke:SetKeyValue("spawnradius", 10)
				Smoke:SetKeyValue("emittime", 300)
				Smoke:SetKeyValue("firesprite", "sprites/firetrail.spr")
				Smoke:SetKeyValue("smokesprite", "sprites/whitepuff.spr")
				Smoke:SetPos(self.Entity:GetPos())
				Smoke:SetParent(self.Entity)
				Smoke:Spawn()
				Smoke:Activate()
				Smoke:Fire("kill","", 1)
			end
		end
	else
		self:ToggleOnOff(false)
	end
end

local chargetimer = 0

function ENT:PhysicsUpdate( phys )
	if (phys:IsMoveable() and self.connectedtovein) then
		self:SetPos(self.vein:GetPos())
		local ang = self.vein.hitnormal:Angle()
		ang.pitch = ang.pitch + 90
		self:SetAngles(ang)
		phys:EnableMotion(false) -- Freezes the object in place.
	end
end

function ENT:Think()
	if self.on then
		self:Drill()
	end
	self:NextThink(CurTime() + 1)
	return true
end

function ENT:PhysgunPickup()
	if self.connectedtovein then
		return false
	else
		return true
	end
end

function ENT:GravGunPunt()
	if self.connectedtovein then
		return false
	else
		return true
	end
end

function ENT:GravGunPickupAllowed()
	if self.connectedtovein then
		return false
	else
		return true
	end
end

function ENT:AcceptInput(name,activator,caller)

end